package com.lemon.smartsafetynew.ui.activity.electrical;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.TextView;

import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.listener.RecyclerTClickListener;
import com.lemon.smartsafetynew.entity.electrical.ElectricalKeyVo;
import com.lemon.smartsafetynew.ui.activity.base.SwipeBackActivity;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafetynew.entity.electrical.ElectricalItemVo;
import com.lemon.smartsafetynew.entity.electrical.ElectricialRealTimeVo;
import com.lemon.smartsafetynew.net.services.ElectricalServices;
import com.lemon.smartsafetynew.ui.adapter.electrical.ElectricialListItemAdapter;
import com.lemon.smartsafetynew.util.constants.KeyConstants;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;

/**
 * 实时监测 -- 电气火灾监测
 * Created by Andrew on 2018/3/12.
 */

public class ElectricalSafeSensorListActivity extends SwipeBackActivity
        implements RecyclerTClickListener<ElectricalKeyVo> {

    @Bind(R.id.monitor_title_tv)
    TextView monitorTitleTv;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;

    private static ElectricalItemVo itemVo;
    List<ElectricalKeyVo> realKeyVo;
    private ElectricialListItemAdapter electricialListItemAdapter;


    private Timer timer;

    @Override
    protected void initTitle() {
        this.setBarTitle("监测详情");
    }

    @Override
    protected void callFinish() {
        AppManager.getAppManager().finishActivity(this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_monitor_detail;
    }

    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();

        Bundle bundle;
        bundle = getIntent().getExtras();

        if (bundle != null) {
            itemVo = (ElectricalItemVo) bundle.getSerializable(KeyConstants.KEY_ELECTRICAL_ITEM);
        }
    }

    @Override
    protected void initViews() {
        super.initViews();
        realKeyVo = new ArrayList<>();
        monitorTitleTv.setText(com.lemon.smartsafetynew.util.common.CommonUtil.avoidNullString(itemVo.getArea())
                + " " + com.lemon.smartsafetynew.util.common.CommonUtil.avoidNullString(itemVo.getLocation()));

    }

    @Override
    protected void onResume() {
        super.onResume();

        startGetNetData();
    }

    @Override
    public void onItemClick(ElectricalKeyVo data, int position) {
            Bundle bundle = new Bundle();
            bundle.putSerializable(KeyConstants.KEY_ELECTRICAL_SENSOR_INFO, data);
            bundle.putSerializable(KeyConstants.KEY_ELECTRICAL_ITEM, itemVo);
            UIHelper.showActivity(this, bundle, ElectricalSafeSensorActivity.class);
    }


    private void getNetData() {
        LemonRequestParams params = new LemonRequestParams("");
        params.put("deviceId", itemVo.getDeviceId());
        ElectricalServices.init().getElectricalRealTimeKey(params);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(HttpCallbackEvent event) {

        if (KeyConstants.URL_ELECTRICAL_REAL_TIME_KEY.equals(event.getTag())) {  //获得监测点传感器列表
            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
                mHUDUtil.showHUD();
            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow() && recyclerView != null) {
                mHUDUtil.hidden();
                if (Constants.Result.SUCCESS == event.getEventResult()) {
                    realKeyVo = (List<ElectricalKeyVo>) event.getObj();
                    initKeyValue();
                } else if (Constants.Result.ERROR == event.getEventResult()) {
                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            callFinish();
                        }
                    });
                }
            }
        } else if (KeyConstants.URL_ELECTRICAL_REAL_TIME_VALUE.equals(event.getTag())) {
            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
                mHUDUtil.showHUD();
            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow() && recyclerView != null) {
                mHUDUtil.hidden();
                if (Constants.Result.SUCCESS == event.getEventResult()) {
                    ElectricialRealTimeVo vo = (ElectricialRealTimeVo) event.getObj();
                    Map<String, Object> mMap = vo.getRealTimeData();
                    List<String> unNormal = vo.getUnnormalCodes();
                    for (int i = 0; i < realKeyVo.size(); i++) {
                        ElectricalKeyVo keyVo = realKeyVo.get(i);
                        String code = keyVo.getCode();
                        keyVo.setKey(keyVo.getDesc()+"("+keyVo.getUnit()+")");
                        if(mMap != null) {
                            if (mMap.containsKey(code)) {
                                keyVo.setValue((String) mMap.get(code));
                                if (unNormal.contains(code)) {
                                    keyVo.setStatus("0");
                                }else{
                                    keyVo.setStatus("1");
                                }
                            }
                        }else{
                            keyVo.setValue("");
                            keyVo.setStatus("");
                        }
                        if(electricialListItemAdapter != null){
                            electricialListItemAdapter.notifyDataSetChanged();
                        }else{
                            LinearLayoutManager layoutManager = new LinearLayoutManager(IApplication.context(), LinearLayoutManager.VERTICAL, false);
                            recyclerView.setLayoutManager(layoutManager);
                            electricialListItemAdapter = new ElectricialListItemAdapter(realKeyVo, this);
                            recyclerView.setAdapter(electricialListItemAdapter);
                        }
                    }
                } else if (Constants.Result.ERROR == event.getEventResult()) {
                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            callFinish();
                        }
                    });
                }
            }
        }
    }

    private void initKeyValue() {
        if (realKeyVo != null && realKeyVo.size() > 0) {
            LemonRequestParams params1 = new LemonRequestParams("");
            params1.put("deviceId", itemVo.getDeviceId());
            ElectricalServices.init().getElectricalRealTimeValue(params1);
        }
    }

    /**
     * 按频率获取一次数据
     */
    private final static int TIMES = 120; //秒

    private void startGetNetData() {

        timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                getNetData();
            }
        }, 0, 1000 * TIMES);
    }

    /**
     * 清理对象，缓存等
     */
    private void clear() {

        if (timer != null) {
            timer.cancel();
            timer.purge();
            timer = null;
        }
        OkHttpUtils.getInstance().cancelTag(KeyConstants.URL_ELECTRICAL_SENSOR_LIST);
    }

    @Override
    protected void onPause() {
        super.onPause();
        clear();
    }

}
